import 'dart:convert';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:dio/dio.dart';
import 'package:eplorex/pages/community/moment/visible_page.dart';
import 'package:eplorex/providers/user_context.dart';
import 'package:eplorex/utils/HttpUtil.dart';
import 'package:eplorex/widgets/gallery.dart';
import 'package:flutter/material.dart';

import '../../../utils/ImagePickerUtils.dart';
import '../../map/map_select_location_page.dart';

// PUBLIC(0, "公开"),
// PRIVATE(1, "私有"),
// PARTIAL_SEEN(2, ""),
// PARTIAL_NO_SEEN(3, "部分不可见"),
// UNKOWN(99, "未定义");
enum VisibleEnum {
  PUBLIC(0, "公开"),
  PRIVATE(1, "私有"),
  PARTIAL_SEEN(2, "部分可见"),
  PARTIAL_NO_SEEN(3, "部分不可见"),
  UNKOWN(99, "未定义");

  final num code;
  final String desc;

  const VisibleEnum(this.code, this.desc);

  static VisibleEnum findById(num code) {
    return VisibleEnum.values
        .firstWhere((element) => element.code == code, orElse: () => UNKOWN);
  }
}

class MomentCreatePage extends StatefulWidget {
  final Map arguments;

  MomentCreatePage({super.key, required Map this.arguments});

  @override
  State<MomentCreatePage> createState() => _MomentCreatePageState();
}

class _MomentCreatePageState extends State<MomentCreatePage> {
  final _textController = TextEditingController();
  final _titleController = TextEditingController();
  String? _curCity;
  String? _districtCode;
  num _visible = 0;
  List<FileWrapper> _imageFiles = [];
  AMapFlutterLocation? aMapFlutterLocation;

  @override
  void dispose() {
    super.dispose();
    _titleController.dispose();
    _textController.dispose();
  }

  Future<void> _selectImage(BuildContext context) async {
    var selectedImage = await selectImage(context);
    setState(() {
      _imageFiles.addAll(selectedImage);
    });
  }

  Future<void> _publish() async {
    String title = _titleController.text;
    String text = _textController.text;
    List<FileWrapper> images = _imageFiles;
    // Create a new multipart request
    List<String>? paths = await compressAndUploadPics(_imageFiles);
    if (paths == null) {
      return;
    }

    List<Object> multiMedia = [];
    for (int idx = 0; idx < paths.length; idx++) {
      var picItem = {
        "name": "",
        "type": "pic",
        "url": paths[idx],
        "width": images[idx].size.width,
        "height": images[idx].size.height,
        "size": await images[idx].file.length(),
        "cover": true
      };
      multiMedia.add(picItem);
    }

    Response? saveResponse =
        await HttpUtil.getInstance().post('/api/moment/v1/save',
            data: jsonEncode({
              "creatorId": UserContext.cxt()?.uid,
              "title": title,
              'userPosition': _districtCode,
              'visible': _visible,
              "content": text,
              "topics": [1, 2, 3],
              "multiMedia": multiMedia
            }));

    print('Publish successful! $saveResponse');
  }

  Widget buildPhotoItem(BoxConstraints constraints, FileWrapper imageFile) {
    var width = (constraints.maxWidth - 8 * 2) / 3;
    return GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
          builder: (_) => GalleryWidget(
              initialIndex: _imageFiles.indexOf(imageFile),
              items: _imageFiles,
              isBarVisible: true),
        ));
      },
      child: Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(3)),
        child: Image.file(
          imageFile.file,
          width: width,
          height: width,
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  Widget buildAddBtn(BoxConstraints constraints) {
    var width = (constraints.maxWidth - 8 * 2) / 3;
    return GestureDetector(
      onTap: () {
        _selectImage(context);
      },
      child: Container(
        color: Colors.black12,
        width: width,
        height: width,
        child: Icon(
          color: Colors.black38,
          Icons.add,
          size: 50,
        ),
      ),
    );
  }

  Widget buildPhotoList() {
    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
      return Wrap(
        alignment: WrapAlignment.start,
        spacing: 5,
        runSpacing: 5,
        children: [
          ..._imageFiles
              .map((imageFile) => buildPhotoItem(constraints, imageFile))
              .toList(),
          if (_imageFiles.length < 9) buildAddBtn(constraints)
        ],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Colors.white,
      appBar: AppBar(title: Text(''), actions: [
        Padding(
          padding: const EdgeInsets.all(12.0),
          child: ElevatedButton(
              style: ButtonStyle(
                  shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                    RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.circular(5.0), // 调整这里的数值来设置圆角的大小
                    ),
                  ),
                  backgroundColor: MaterialStateProperty.all(Colors.blue)),
              onPressed: () {
                _publish();
                Navigator.pop(context);
              },
              child: const Text(
                '发布',
                style: TextStyle(color: Colors.white),
              )),
        )
      ]),
      body: ListView(
        children: [
          buildPublishView(),
          SizedBox(height: 16),
          ListTile(
            leading: Image(
              image: AssetImage('images/preview-open.png'),
              width: 25,
            ),
            title: Text(
              '谁可见',
              style: TextStyle(fontSize: 16),
            ),
            trailing: Wrap(
              children: [
                Text(
                  '${VisibleEnum.findById(_visible).desc}',
                  style: TextStyle(fontSize: 16),
                ),
                const Image(
                  image: AssetImage("images/arrow_right_icon.png"),
                  width: 20,
                )
              ],
            ),
            onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (_) => VisiblePage(
                          valueChanged: (num value) {
                            _visible = value;
                            setState(() {});
                          },
                          initialVisible: _visible,
                        ))),
          ),
          ListTile(
            leading: Image(
              image: AssetImage('images/map_location_icon.png'),
              width: 25,
            ),
            title: Text(
              (_curCity ?? '所在位置'),
              style: TextStyle(fontSize: 16),
            ),
            onTap: () {
              getCurLocation();
            },
          ),
        ],
      ),
    );
  }

  Widget buildPublishView() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10),
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10), color: Colors.white60),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextField(
            controller: _textController,
            decoration: InputDecoration(
              filled: true,
              fillColor: Colors.white,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide.none,
              ),
              hintText: '分享你的想法...',
            ),
            maxLines: 3,
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _titleController,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.zero,
              filled: true,
              fillColor: Colors.white,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(2),
                borderSide: BorderSide.none,
              ),
              hintText: '标题',
            ),
            style: TextStyle(fontSize: 18),
          ),
          SizedBox(height: 16),
          _imageFiles != null ? buildPhotoList() : Text("添加图片"),
        ],
      ),
    );
  }

  void getCurLocation() {

    // Navigator.of(context)
    //     .push(MaterialPageRoute(builder: (_) => MapSelectLocation()));

    aMapFlutterLocation = AMapFlutterLocation()
      ..setLocationOption(AMapLocationOption())
      ..onLocationChanged().listen((event) {
        if (event['city'] != null) {
          setState(() {
            var city = event['city'] as String;
            var district = event['district'] as String;
            _curCity = city + " " + district;
            _districtCode = event['adCode'] as String;
          });
        }
        aMapFlutterLocation?.stopLocation();
      })
      ..startLocation();
  }
}
